/*************************************************************************
	> File Name: fork_file_race.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Tue 08 Jul 2014 03:31:16 PM CST
 ************************************************************************/

/*
 * 至于为什么会出现
 * test 1st
 *
 * this is in child        4227
 * test 2nd         parent 4227
 * test 1st         
 *
 * test 2nd         parent 4226
 *
 * 这是因为子进程copy了父进程的代码段(即整个程序[当然不包括自己])
 * 前面3行都是子进程打印的
 *
 * 因为是fprintf (同printf) 需要在exit的时候刷新输入输出流(将内容写入文件)
 * 而子进程先于父进程运行,子进程退出并刷新缓冲区后
 *父进程才运行,最后将缓冲区中的 test 1st 和 test 2nd parent 4226刷新(写入文件)
 */

#include"head.h"

int main(int argc,char *agrv[])
{
    FILE *fp;
    pid_t pid;

    char msg1[]="test 1st";
    char msg2[]="test 2nd";

    printf("(parent before) PID: %d\n",getpid());

    if((fp=fopen("Test","w"))==NULL)
        err("fopen");

    fprintf(fp,"%s\n\n",msg1);
            if(errno)
                err("(child) fprintf");

    switch(pid=fork()){
        case -1:
            err("fork");
        case 0:
            printf("(child) PID: %d\n",getpid());
            fprintf(fp,"%s\t","this is in child");
            fprintf(fp,"%d\n",getpid());
            if(errno)
                err("[ERROR](child) fprintf");
            else
                printf("(child) write done\n");
            //_exit(EXIT_SUCCESS);
        default:
            sleep(3);
            wait(NULL);
            printf("(%s) PID: %d\n",(pid==0)?"child(copy of parent)":"parent",getpid());
            fprintf(fp,"%s\t",msg2);
            fprintf(fp,"%s\t","parent");
            fprintf(fp,"%d\n",getpid());
            if(pid>0){
            fclose(fp);
            if(errno)
                err("fclose");
            }
            exit(EXIT_SUCCESS);
    }
   
}
